import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Comment } from './entities/comment.entity';
import { CreateCommentDto } from './dto/create-comment.dto';
import { Topic } from '../topic/entities/topic.entity';
import { WxUserService } from '../wxuser/wxuser.service';

@Injectable()
export class CommentService {
  constructor(
    @InjectRepository(Comment)
    private readonly commentRepository: Repository<Comment>,
    @InjectRepository(Topic)
    private readonly topicRepository: Repository<Topic>,
    private readonly wxUserService: WxUserService,
  ) {}

  async create(createCommentDto: CreateCommentDto) {
    const { topicId, userId } = createCommentDto;
    const topic = await this.topicRepository.findOne({
      where: { id: topicId },
    });
    if (!topic) {
      throw new NotFoundException('话题不存在');
    }
    const wxUser = await this.wxUserService.getUserById(userId);
    const userInfo = {
      username: wxUser?.username || '未知用户',
      avatar: wxUser?.avatar || '',
    };
    const comment = this.commentRepository.create({
      ...createCommentDto,
    });
    const savedComment = await this.commentRepository.save(comment);
    return { ...savedComment, ...userInfo };
  }

  async findByTopicId(topicId: number) {
    const data = await this.commentRepository.find({ where: { topicId } });
    const total = await this.commentRepository.count({ where: { topicId } });
    const dataWithUserInfo = await Promise.all(
      data.map(async (comment) => {
        const wxUser = await this.wxUserService.getUserById(comment.userId);
        return {
          ...comment,
          username: wxUser?.username || '未知用户',
          avatar: wxUser?.avatar || '',
        };
      }),
    );
    return { data: dataWithUserInfo, total };
  }
  // 新增通过用户 ID 获取评论的方法
  async findByUserId(userId: number) {
    const data = await this.commentRepository.find({ where: { userId } });
    const total = await this.commentRepository.count({ where: { userId } });
    const dataWithUserInfo = await Promise.all(
      data.map(async (comment) => {
        const wxUser = await this.wxUserService.getUserById(comment.userId);
        const topic = await this.topicRepository.findOne({
          where: { id: comment.topicId },
          select: ['mediaUrl'], // 只查询 mediaUrl 字段
        });
        return {
          ...comment,
          username: wxUser?.username || '未知用户',
          avatar: wxUser?.avatar || '',
          mediaUrl: topic?.mediaUrl || null, // 添加 mediaUrl 到返回结果
        };
      }),
    );
    return { data: dataWithUserInfo, total };
  }
}
